<template>
  <basic-container :btnFlag=true>
    <div class="card-border">
      <card-header :header-data="headerData"></card-header>
      <el-steps :active="0" simple style="margin-top: 10px">
        <el-step title="基本信息入库" icon="el-icon-edit"></el-step>
        <el-step title="相关课题入库" icon="el-icon-upload"></el-step>
        <el-step title="相关报告入库" icon="el-icon-picture"></el-step>
      </el-steps>
      <div style="font-weight:600;margin-top: 20px;">成果信息:</div>
      <el-form
        label-width="130px"
        :model="projectForm"
        style="padding-right: 30px;"
        :rules="infosrules"
        ref="projectForm"
      >
        <el-row style="margin-top: 27px;">
          <el-col :span="12">
            <el-col :span="20">
              <el-form-item class="form-item" label="文号" prop="releaseNo">
                <el-input
                  v-model="projectForm.releaseNo"
                  placeholder="请输入"
                  style="width: 280px"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="规划名称" prop="title">
              <el-input v-model="projectForm.title" placeholder="请输入规划名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-col :span="20">
              <el-form-item class="form-item" label="规划类型" prop="category">
                <el-select
                  v-model="projectForm.category"
                  placeholder="申报规划类型"
                  readonly
                  style="width: 280px;"
                >
                  <el-option
                    v-for="item in categoryDic"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-item" label="规划期限" prop="startDate" style="float: left">
              <el-date-picker
                style="width: 130px"
                v-model="projectForm.startDate"
                type="year"
                placeholder="选择年"
                value-format="yyyy"
                format="yyyy"
              >
              </el-date-picker>
              <span style="margin-left: 5px;margin-right: 5px">至</span>
              <el-date-picker
                style="width: 130px"
                v-model="projectForm.endDate"
                type="year"
                placeholder="选择年"
                value-format="yyyy"
                format="yyyy"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-col :span="20">
              <el-form-item class="form-item" label="申报(牵头)单位" prop="orgCode">
                <el-input v-model="projectForm.orgName" placeholder="请选择申报(牵头)单位"
                          @click.native="deptVisible = true"></el-input>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-col :span="20">
              <el-form-item class="form-item" label="发布时间" prop="releaseDate">
                <el-date-picker
                  style="width: 100%"
                  v-model="projectForm.releaseDate"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format=" yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  @change="gettime()"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="form-item" label="审批机关级别" prop="approvingAuthorityLevel">
              <el-select
                v-model="projectForm.approvingAuthorityLevel"
                placeholder="请选择"
                style="width: 280px;"
              >
                <el-option
                  v-for="item in authorityLevelDic"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-item" label="审批机关性质" prop="approvingAuthorityNature">
              <el-select
                v-model="projectForm.approvingAuthorityNature"
                placeholder="请选择"
                style="width: 280px;"
              >
                <el-option
                  v-for="item in natureDIC"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="form-item" label="发布层级" prop="planningLevel">
              <el-select
                v-model="projectForm.planningLevel"
                placeholder="请选择"
                style="width: 280px"
              >
                <el-option
                  v-for="item in planningLevelDic"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-item" label="发布等级" prop="planningRank">
              <el-select
                v-model="projectForm.planningRank"
                placeholder="请选择"
                style="width: 280px"
              >
                <el-option
                  v-for="item in planningRankDic"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item class="form-item" label="联系人" prop="contactName">
              <el-input v-model="projectForm.contactName" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item class="form-item" label="联系电话" prop="contactNumber">
              <el-input v-model="projectForm.contactNumber" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="经费来源" prop="financialSource">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入经费来源"
                v-model="projectForm.financialSource"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="立项依据" prop="basis">
              <quill-editor ref="basisEditor"
                            v-model="projectForm.basis"
                            :content="basisContent"
                            :options="basisOption">
              </quill-editor>
              <el-upload
                class="uploadFile"
                action="string"
                :limit="1"
                :http-request="basisSubmitUploadMixin"
                :on-change="basisFileChangeMixin"
                :on-preview="basishandlePreviewMixin"
                :on-remove="basishandleRemoveMixin"
                :auto-upload="true"
                :file-list="basisFileListMixin">
                <el-button size="small" type="primary">附件上传</el-button>
                <div slot="tip" class="el-upload__tip" style="margin-top: -8px;">请上传依据材料</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="主要内容" prop="content">
              <quill-editor ref="contentEditor"
                            v-model="projectForm.content"
                            :content="content"
                            :options="editorOption">
              </quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="规划文本">
              <el-upload
                class="upload-demo"
                ref="upload"
                :limit="1"
                action="string"
                :http-request="submitUploadtextMixin"
                :on-preview="handlePreviewtextMixin"
                :on-remove="handleRemovetextMixin"
                :file-list="fileListtextMixin"
                :auto-upload="true"
                :on-change="fileChangetextMixin">
                <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">请上传规划文本</div>
              </el-upload>
            </el-form-item>
            <el-col :span="22">
              <el-form-item class="form-item" label="相关材料">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="string"
                  :http-request="submitUploadMixin"
                  :on-preview="handlePreviewMixin"
                  :on-remove="handleRemoveMixin"
                  :file-list="fileListMixin"
                  :auto-upload="true"
                  :on-change="fileChangeMixin">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">上传工作方案、工作计划等相关材料</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item class="form-item" label="是否公开" prop="isOpen">
              <el-radio-group v-model="projectForm.isOpen" prop="isOpen">
                <el-radio :label='1'>公开</el-radio>
                <el-radio :label='0'>非公开</el-radio>
                <el-radio :label='2'>部分公开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item class="form-item"
                          label="规划文本(部分公开)"
                          prop="halfOpenTextId"
                          :required=true
                          v-if="txtHalfOpenFlag">
              <el-upload class="upload-demo"
                         ref="upload"
                         :limit="1"
                         :on-exceed="tipFileOne"
                         action="string"
                         :http-request="submitUploadtextHalfMixin"
                         :on-preview="handlePreviewtextHalfMixin"
                         :on-remove="handleRemovetextHalfMixin"
                         :file-list="fileListtextHalfMixin"
                         :auto-upload="true"
                         :on-change="fileChangetextHalfMixin">
                <el-button slot="trigger"
                           size="small"
                           type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="form-submit">
        <el-button type="success"
                   @click.stop="commitList('0')">确认并关闭</el-button>
        <el-button type="info" @click.stop="goBack()">关闭</el-button>
        <el-button type="primary"
                   @click.stop="commitList('1')">下一步</el-button>
      </div>

      <el-dialog
        title=""
        :visible.sync="dialogVisiblesubmit"
        width="70%"
        :before-close="handleClosesubmit">
        <h2 style="margin-top: -20px;margin-bottom: -10px;">请确认所填信息：</h2>
        <div class="dial">
          <submit-validate :planningFormData = 'projectForm'></submit-validate>
        </div>
        <div style="text-align: center;">
        <span slot="footer" class="dialog-footer">
           <el-button type="primary" @click="commitYes">确定提交</el-button>
           <el-button @click="dialogVisiblesubmit = false">取 消</el-button>
          <el-button type="primary" @click="skip()" v-if="skipOrNot">跳过</el-button>
          </span>
        </div>
      </el-dialog>
      <dept-select :visible="deptVisible" :province="province" @getSelectInfo="getSelectInfo" @cancel="cancelDept"></dept-select>
    </div>
  </basic-container>
</template>
<script>
  import {PROJECT_DIC} from "@/const/dict";
  import {resultRules} from "@/const/infoRules";
  import {resultEdit, resultDetail} from "@/api/planning/result";
  import getDetailData from "@/mixins/getDetailData";
  import {getDeptTree, UploadFile, filedownload, getfileinfo, getfileinfopage} from "@/api/system";
  import {mapGetters} from "vuex";
  import relatedfile from "@/mixins/relatedfile";
  import basisfile from "@/mixins/basisfile";
  import textfile from "@/mixins/textfile";
  import textHalffile from "@/mixins/textHalffile";
  import submitValidate from "@/components/planning/submitValidate"

  export default {
    name: "resultAdd",
    mixins: [relatedfile, basisfile, getDetailData(), textfile,textHalffile],
    components: {
      submitValidate
    },
    data() {
      return {
        headerData: {
          title: '成果入库'
        },
        content: '',
        editorOption: {
          modules: {
            toolbar: null
          },
          placeholder: '请输入主要内容'
        },
        publicPath: process.env.BASE_URL,
        detailData: [],
        categoryDic: PROJECT_DIC.CATEGORY,
        planningLevelDic: PROJECT_DIC.PLANNING_LEVEL,
        planningRankDic: PROJECT_DIC.PLANNING_RANK,
        isOpen: PROJECT_DIC.isOpen,
        authorityLevelDic: PROJECT_DIC.APPROVING_AUTHORITY_LEVEL,
        natureDIC: PROJECT_DIC.APPROVING_AUTHORITY_NATURE,
        dialogVisible: false,
        dialogVisiblesubmit: false,
        infotype: "",
        value: "",
        textcontent: "",
        radio: "",
        idsarray: '',  //附件id数组，用于相关材料多个附件传给详情组件
        multiplefiles: [],  //多个文件的信息
        // fileListtext:[],
        basisContent: '',
        basisOption: {
          // something config
          modules: {
            toolbar: null
          },
          placeholder: '请输入立项依据'
        },
        filenametemp: '',
        basisfilename: '',
        projectForm: {
          year: 2019,
          fileId: null,
          textId: null,
          basisFileId: null,
          halfOpenTextId: null,
          relateFiles:null,
        },
        deptVisible: false,//申报单位树弹框标志
        province: false,
        infosrules: resultRules,
        txtHalfOpenFlag:false,
        typeControl:null,//区别下一步还是保存并关闭
        skipOrNot:false,
      }
    },
    created() {
      resultDetail(this.$route.params.id).then(response => {
        if (response.data.code == '0') {
          var records = response.data.data;
          this.projectForm = records;

          var basisFileId = this.projectForm.basisFileId;
          this.setfilelist(basisFileId, 'basis');

          var fileId = this.projectForm.fileId;
          this.setfilelistrelated(fileId);

          var textId = this.projectForm.textId;
          this.setfilelist(textId, 'text');

          var halfOpenTextId = this.projectForm.halfOpenTextId;
          this.setfilelist(halfOpenTextId, 'halfOpenText');

          if(this.projectForm.isOpen=='2'){
            this.txtHalfOpenFlag=true;
          }else {
            this.txtHalfOpenFlag=false;
          }

          this.projectForm.startDate = this.dateChange(records.startDate);
          this.projectForm.endDate = this.dateChange(records.endDate);
          this.headerData.title = records.title
        }
      })
    },
    computed: {
      editor() {
        return this.$refs.contentEditor.quill
      },
      basisEditor() {
        return this.$refs.basisEditor.quill
      },
      ...mapGetters([
        "deptInfo"
      ])
    },
    mounted() {
      // 设置编辑器高度
      this.editor.container.style.height = '150'
    },
    watch:{
      'projectForm.isOpen'(val) {
        if (val == '2') {
          this.txtHalfOpenFlag = true;
        }else {
          this.projectForm.halfOpenTextId = null;
          this.fileListtextHalfMixin = [].concat();
          this.txtHalfOpenFlag = false;
        }
      }
    },
    methods: {
      // 返回首页
      goHome() {
        this.$router.push({path: "/wel"});
      },
      // 返回首页
      goBack () {
        this.$router.push({ path: "/listFeedback/detail/cgrk" });
      },
      dateChange: function (date) {
        if (date) {
          var date = new Date(Date.parse(date));
          var newDate = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
          return newDate;
        }
      },
      gettime() {
        var date = this.projectForm.releaseDate.split("-");
        this.projectForm.year = parseInt(date[0])
      },

      uploadBefore(file, done, loading) {
        done();
        this.$message.success("上传前的方法");
      },
      uploadAfter(res, done, loading) {
        done();
        this.$message.success("上传后的方法");
      },
      handleSubmit(form) {
        this.$message.success(JSON.stringify(this.form));
      },
      handleClose(done) {
        this.$confirm("确认关闭？")
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      handleClosesubmit(done) {
        this.$confirm("确认关闭？")
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      // // 暂存
      // projectTS() {
      //   this.$refs.projectForm.validate(valid => {
      //     if (valid) {
      //       registerInfo(this.projectForm).then(response => {
      //         if (response.data.code == 0) {
      //           this.$notify({
      //             title: "成功",
      //             message: "暂存成功",
      //             type: "success",
      //             duration: 2000
      //           });
      //           this.$router.go(-1);
      //         }
      //       });
      //     }
      //   })
      // },
      // 提交
      resultEdit() {
        this.$refs.projectForm.validate(valid => {
          if (valid) {
            resultEdit(this.projectForm, this.$route.params.id).then(response => {
              if (response.data.code == 0) {
                this.$notify({
                  title: "成功",
                  message: "修改成功",
                  type: "success",
                  duration: 2000
                });
                if(this.typeControl=='0'){
                  this.$router.push({
                    path: "/listFeedback/detail/cgrk"
                  });
                }else if(this.typeControl=='1'){
                  //转到下一步
                  let src = `/resultAddSubject/detail/${this.$route.params.id}`;
                  this.$router.push({
                    path: src
                  })
                }
              }
            });
          }
        });
      },
      //确认提交的弹出框
      async commitList(typeControl) {
        if (this.fileListMixin.length == 0) {
          this.multiplefiles = [];
        }
        var arr = [];
        this.idsarray = '';
        if (this.fileListMixin.length != 0) {
          for (var item in this.fileListMixin) {
            arr.push(this.fileListMixin[item].url);
          }
          this.idsarray = arr.join(",");
        }
        if (this.idsarray != "") {
          await getfileinfopage(Object.assign({
            current: 1,
            size: 100,
            fileIds: this.idsarray
          })).then(response => {
            this.multiplefiles = response.data.data.records;
          }).catch(
          )
        }
        this.$refs.projectForm.validate(valid => {
          if (valid) {
            this.projectForm.startDate = this.projectForm.startDate.substring(0, 4);
            this.projectForm.endDate = this.projectForm.endDate.substring(0, 4);
            if (parseInt(this.projectForm.startDate) > parseInt(this.projectForm.endDate)) {
              this.$notify({
                title: "提醒",
                type: "warning",
                message: "规划期限开始时间不能大于结束之间",
                duration: 2000
              });
              return;
            }
            if (this.projectForm.textId == null) {
              this.$confirm("请上传规划文本", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
            } else {
              this.dialogVisiblesubmit = true;
            }
            //将多个相关材料的附件id拼成逗号隔开的字符串放在 this.projectForm.fileId 中
            var arr = [];
            for (var item in this.fileListMixin) {
              arr.push(this.fileListMixin[item].url);
            }
            this.projectForm.fileId = arr.join(",");
            this.projectForm.relateFiles = arr;//用于确认提交弹窗中相关材料的显示
            this.getresultDetailDate(this.projectForm);
            this.typeControl = typeControl;
            if(typeControl=='1'){
              this.skipOrNot=true;
            }else if(typeControl=='0'){
              this.skipOrNot=false;
            }
          }
        });
      },
      commitYes() {
        this.resultEdit();
      },
      //申报单位点击事件
      orgCodeClick(data) {
        this.projectForm.orgCode = data.id;
        this.projectForm.orgName = data.name;
        this.orgCodeVisiblesubmit = false
      },
      getSelectInfo(deptId, deptName) {
        this.projectForm.orgCode = deptId;
        this.projectForm.orgName = deptName;
        this.deptVisible = false;
      },
      cancelDept(eptId, deptName) {
        this.deptVisible = false;
      },
      // 下载文件
      download(data, filename) {
        if (data == null) {

        } else {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click()
        }
      },
      setfilelist(fileId, type) {
        if(fileId!=null&&fileId!=undefined&&fileId != ''){
          getfileinfo(fileId).then(response => {
            if (response.data.code == 0) {
              if (response.data.data != null) {
                var filenametemp = response.data.data.fileName + "." + response.data.data.extend;
                if (type == 'basis') {
                  this.basisFileListMixin = [{name: filenametemp, url: fileId}];
                  this.projectForm.basisFileId = fileId;
                  this.basisfilename = filenametemp;
                } else if (type == 'text') {
                  this.fileListtextMixin = [{name: filenametemp, url: fileId}];
                  this.projectForm.textId = fileId;
                  this.filenametemptext = filenametemp;
                } else if (type == 'halfOpenText') {
                  this.fileListtextHalfMixin = [{name: filenametemp, url: fileId}];
                  this.projectForm.halfOpenTextId = fileId;
                  this.filenametemptextHalf = filenametemp;
                }

              }
            }
          })
        }
      },
      async setfilelistrelated(fileIds) {
        this.projectForm.fileId = fileIds;
        if (fileIds != "" && fileIds != null) {
          await getfileinfopage(Object.assign({
            current: 1,
            size: 100,
            fileIds: fileIds
          })).then(response => {
            var records = response.data.data.records;
            if (records.length != 0) {
              for (var item in records) {
                if (records[item] != null) {
                  this.fileListMixin.push({
                    name: records[item].fileName + records[item].extend,
                    url: records[item].fileId
                  })
                }
              }
            }
          }).catch(
          )
        }
      },
      //直接跳过不提交表单，去录入课题
      skip(){
        //转到下一步
        let src = `/resultAddSubject/detail/${this.$route.params.id}`;
        this.$router.push({
          path: src
        })
      }
    }
  };
</script>

<style lang="scss" scoped>
  .step-title {
    display: inline-block;
    border-bottom: solid #ec950a;
    padding-bottom: 10px;
    font-weight: 600;
  }

  .step-button {
    float: right;
  }

  .step-img {
    width: 25px;
    position: relative;
    left: 0px;
    top: 7px;
  }

  .step-group {
    margin: 5rem 0;
  }

  .form-item {
    font-weight: 600;
  }

  .form-group {
    margin-top: 2rem;
  }

  .form-label {
    font-weight: 600;
    margin-right: 2rem;
  }

  .form-padding {
    padding-left: 50px;
  }

  .form-label-small {
    font-size: 14px;
    margin-right: 12px;
    display: inline-block;
    min-width: 101px;
  }

  .form-submit {
    text-align: center;
  }

  .card-border {
    border: 1px solid #d2d2d2;
    padding: 12px;
  }

  .remarksbtn {
    border-radius: 6px;
    padding: 5px 4px;
    margin-left: 10px;
  }

  .dial {
    width: 100%;
    overflow: auto;
    height: 420px;
  }

  .ql-upload {
    background: url("../../../../public/img/user.png");
    background-size: 16px 16px;
    background-position: center center;
    background-repeat: no-repeat;
    /*background: red;*/
  }
</style>
<style>
  .ql-toolbar.ql-snow {
    border: 1px solid #ccc;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
    padding: 0 8px;
  }

  .ql-container.ql-snow {
    height: 12rem;
  }

  .ql-snow.ql-toolbar button, .ql-snow .ql-toolbar button {
    background: url("../../../../public/img/upload.png");
    background-size: 16px 16px;
    background-position: center center;
    background-repeat: no-repeat;
    border: none;
    cursor: pointer;
    display: inline-block;
    float: left;
    height: 24px;
    padding: 3px 5px;
    width: 28px;
  }
</style>




